package leetcode;


import leetcode.vo.ListNode;

import java.util.Arrays;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class addTwoNumbers {


    /**
     * 1 2 3
     * 7 8 9
     * @param args
     */
    public static void main(String[] args) {
        addTwoNumbers a = new addTwoNumbers();
        ListNode n1 = new ListNode();
        n1.val = 2;
        ListNode n2 = new ListNode();
        n2.val = 4;
        ListNode n3 = new ListNode();
        n3.val = 3;
        n1.next = n2;
        n2.next = n3;

        ListNode n11 = new ListNode();
        n11.val = 5;
        ListNode n12 = new ListNode();
        n12.val = 6;
        ListNode n13 = new ListNode();
        n13.val = 4;
        n11.next = n12;
        n12.next = n13;

        ListNode listNode = a.addTwoNumbers(n1, n11);
        System.out.println(listNode);

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        while(l1 != null || l2 != null){
            int i1  = l1 == null ? 0 : l1.val;
            int i2  = l2 == null ? 0 : l2.val;
            int sum = i1 + i2 + carry;
            if(head  == null){
                head = tail = new ListNode(sum % 10);
            }else{
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        if(carry > 0){
            tail.next = new ListNode(carry);
        }
        return head;
    }

//    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//        ListNode head = null, tail = null;
//        while(l1 != null && l2 != null){
//
//        }
//        return null;
//    }

}



